<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2018/8/15
 * Time: 18:43
 */

namespace app\admin\controller;


use think\Db;
use think\Request;
use app\admin\model\Mechanism as MechanismModel;//机构
use app\admin\model\MechanismMember as MechanismMemberModel;//机构管理员
use app\admin\model\Area as AreaModel;//地区
use app\admin\model\MechanismMien as MechanismMienModel;//机构风采

class Mechanism extends Base
{
    /**
     * 机构列表展示
     * @return mixed|\think\response\Json
     */
    public function index(){
        if(Request::instance()->isAjax()){
            $params = input('param.');
            $where = [];
            //机构名称模糊查询
            if(isset($params['key']) && $params['key'] != '')
            {
                $where['um.mechanism_name'] = ['like', "%" . $params['key'] . "%"];
            }
            //审核状态
            if(isset($params['mechanism_status']) && $params['mechanism_status'] != 0){
                $where['um.mechanism_status'] = $params['mechanism_status'];
            }
            $page = input('page') ? input('page') : 1;
            $limits = input('limit') ? input('limit') : 10;// 获取总条数;
            $field = 'um.mechanism_code, um.mechanism_name, um.mechanism_create_time, um.mechanism_allow_time, 
            um.mechanism_phone, um.mechanism_address, um.mechanism_create_code, um.mechanism_type, um.mechanism_status, 
            ua1.district as province, ua2.district as city, ua3.district as district, um1.mechanism_name as parent_name, 
            um.mechanism_id, um.next_mechanism';
            $mechanismModel = new MechanismModel();
            $lists = $mechanismModel->getMechanismLists($where, $field, $page, $limits);
            $count = $mechanismModel->getCount($where);
            foreach($lists as $key=>&$list){
                $list['mechanism_code'] = trim($list['mechanism_code'], ',');
                $num = Db::table('up_mechanism_member')->where('mechanism_id', $list['mechanism_id'])->count();
                $list['mechanismNum'] = $num;
            }
            return json(['code'=>0,'msg'=>'','count'=>$count,'data'=>$lists]);
        }
        if(session('?mechanism_id')){
            session('mechanism_id',null);
        }
        return $this->fetch('mechanism/index');
    }
    
    /**
     * 新建机构
     * @return array|mixed
     */
    public function mechanismAdd(){
        if(Request::instance()->isAjax()){
            $params = input('param.');
            $mechanismModel = new MechanismModel();
            $mechanism_code = ',' . $params['mechanism_code'] . ',';
            $res = $mechanismModel->codeRe($mechanism_code);
            if($res){
                return ['code' => 100, 'data' => '', 'msg' => '机构代码已被使用'];
            }
            $data = [
                'mechanism_code' => $mechanism_code,//机构代码
                'mechanism_name' => $params['mechanism_name'],//机构名称
                'mechanism_intro' => $params['content'],//机构简介
                'mechanism_logo' => $params['images'],//机构logo
                'mechanism_sheng' => $params['sheng'],
                'mechanism_shi' => $params['shi'],
                'mechanism_qu' => $params['qu'],
                'mechanism_create_time' => date('Y-m-d H:i:s'),//注册日期
                'mechanism_allow_time' => date('Y-m-d H:i:s'),//注册日期
                'mechanism_create_code' => $params['mechanism_create_code'],//注册号
                'mechanism_type' => 1,//机构等级
                'mechanism_status' => 2,//审核状态  无需审核，直接审核通过
                'mechanism_address' => $params['mechanism_address'],//组织地址
                'mechanism_phone' => $params['mechanism_phone'],//联系电话
                'first_allow' => 2,//总队第一次审核通过
            ];
            $result = $mechanismModel->insertMechanism($data);
            if($result){
                return ['code' => 200, 'data' =>"", 'msg' => '新建机构成功'];
            }else{
                return ['code' => 100, 'data' => '', 'msg' => '新建机构失败'];
            }
        }
        $areaModel = new AreaModel();
        $province = $areaModel->getProvince();
        $this->assign('province', $province);
        return $this->fetch('mechanism/mechanismadd');
    }
    
    /**
     * 机构风采列表
     * @return mixed|\think\response\Json
     */
    public function mechanismMien(){
        $mechanismModel = new MechanismModel();
        $mechanismMienModel = new MechanismMienModel();
        if(Request::instance()->isAjax()){
            $params = input('param.');
            $page = input('page') ? input('page') : 1;
            $limits = input('limit') ? input('limit') : 10;// 获取总条数;
            $lists = $mechanismMienModel->meinLists($params['id'], $page, $limits);
            $count = $mechanismMienModel->getCount($params['id']);
            return json(['code'=>0,'msg'=>'','count'=>$count,'data'=>$lists]);
        }
        $param = input('param.');
        if(!session('?mechanism_id')){
            session('mechanism_id',$param['id']);
        }
        $info = $mechanismModel->getMechanismCode(session('mechanism_id'));
        $this->assign([
            'info' => $info,
        ]);
        return $this->fetch('mechanism/mechanismmien');
    }
    
    /**
     * 添加风采
     * @return array|mixed
     */
    public function mienAdd(){
        if(Request::instance()->isAjax()){
            $params = input('param.');
            $data = [
                'mien_url' => $params['images'],
                'mien_description' => $params['mien_description'],
                'mechanism_id' => session('mechanism_id')
            ];
            $mechanismMienModel = new MechanismMienModel();
            $res = $mechanismMienModel->insertMien($data);
            if($res){
                return ['code' => 200, 'data' =>"", 'msg' => '添加成功'];
            }else{
                return ['code' => 100, 'data' => '', 'msg' => '添加失败'];
            }
        }
        return $this->fetch('mechanism/mienadd');
    }
    
    /**
     * 修改风采
     * @return array|mixed
     */
    public function mienEdit(){
        $mechanismMienModel = new MechanismMienModel();
        if(Request::instance()->isAjax()){
            $params = input('param.');
            $data = [];
            $data['mien_description'] = $params['mien_description'];
            if(!empty($params['images'])){
                $data['mien_url'] = $params['images'];
            }
            $res = $mechanismMienModel->updataMien($params['mien_id'], $data);
            if($res){
                return ['code' => 200, 'data' =>"", 'msg' => '修改成功'];
            }else{
                return ['code' => 100, 'data' => '', 'msg' => '修改失败'];
            }
        }
        $mien_id = input('id');
        $info = $mechanismMienModel->getOneMien($mien_id);
        $this->assign('info', $info);
        return $this->fetch('mechanism/mienedit');
    }
    
    /**
     * 机构简介
     * @return mixed
     */
    public function mechanismIntro(){
        $param = input('param.');
        $mechanismModel = new MechanismModel();
        $field = 'mechanism_intro';
        $intro = $mechanismModel->getInfo($param['id'], $field);
        $this->assign('intro', $intro);
        return $this->fetch('mechanism/mechanismintro');
    }
    
    /**
     * 修改机构代码
     * @return array|mixed
     */
    public function editCode(){
        $mechanismModel = new MechanismModel();
        $param = input('param.');
        $code = $mechanismModel->getMechanismCode($param['id']);
        if(Request::instance()->isAjax()){
            $params = input('param.');
            $new_code = $params['new_code'];
            $old_code = substr($code['mechanism_code'], 0, -4);
            $newCode = $old_code . $new_code . ',';
            $re = $mechanismModel->codeRe($newCode);//判断代码是否已被使用
            if($re){
                return ['code' => 100, 'data' => '', 'msg' => '机构代码已被使用'];
            }
            $data =[
                'mechanism_code' => $newCode
            ];
            $res = $mechanismModel->updateInfo($param['id'], $data);
            if($res){
                return ['code' => 200, 'data' =>"", 'msg' => '修改成功'];
            }else{
                return ['code' => 100, 'data' => '', 'msg' => '修改失败'];
            }
        }
        $oldCode = trim($code['mechanism_code'], ',');
        $this->assign([
            'oldCode' => $oldCode,
            'id' => $param['id']
        ]);
        return $this->fetch('mechanism/editcode');
    }
    
    /**
     * 机构审核、查看审核
     * @return array|mixed
     */
    public function mechanismAudit(){
        $mechanismModel = new MechanismModel();
        $param = input('param.');
        if(Request::instance()->isAjax()){
            $params = input('param.');
            $data = [];
            if($params['mechanism_status'] == 2){//审核通过
                $data = [
                    'mechanism_status' => $params['mechanism_status'],
                    'mechanism_allow_time' => date('Y-m-d H:i:s'),//创建时间（机构审核通过时间）
                    'first_allow' => 2,//第一次审核通过
                    'mechanism_false_reason' => null,//审核通过，将审核失败原因字段置null
                ];
            }
            if($params['mechanism_status'] == 3){//审核不通过
                $data = [
                    'mechanism_status' => $params['mechanism_status'],
                    'mechanism_false_reason' => $params['mechanism_false_reason'],
                ];
            }
            $res = $mechanismModel->updateInfo($params['id'], $data);
            if($res){
                return ['code' => 200, 'data' =>"", 'msg' => '审核成功'];
            }else{
                return ['code' => 100, 'data' => '', 'msg' => '审核失败'];
            }
        }
        $field = 'umm.mechanism_member_name, um1.mechanism_name as parent_name, ua1.district as province, 
        ua2.district as city, ua3.district as district, um.mechanism_code, um.mechanism_name, um.mechanism_phone, 
        um.mechanism_address, um.mechanism_create_time, um.mechanism_create_code, um.mechanism_intro, um.mechanism_status, 
        um.mechanism_false_reason, um.mechanism_id, um.mechanism_logo';
        $info = $mechanismModel->mechanismAudit($param['id'], $field);
        $info['mechanism_code'] = trim($info['mechanism_code'], ',');
        $this->assign('info', $info);
        return $this->fetch('mechanism/mechanismaudit');
    }
    
    /**
     * 机构管理员列表
     * @return mixed|\think\response\Json
     */
    public function mechanismMember(){
        if(request()->isAjax ()){
            $params = input('param.');
            $where['mechanism_id'] = $params['id'];
            $page = input('page') ? input('page') : 1;
            $limits = input('limit') ? input('limit') : 10;// 获取总条数;
            $field1 = 'id, mechanism_member_phone, mechanism_member_name, mechanism_member_status';
            $mechanismMemberModel = new MechanismMemberModel();
            $lists = $mechanismMemberModel->getMemberList($field1, $where, $page, $limits);
            $count = $mechanismMemberModel->getCountNum($where);
            return json(['code'=>0,'msg'=>'','count'=>$count,'data'=>$lists]);
        }
        $param = input('param.');
        if(!session('?mechanism_id')){
            session('mechanism_id',$param['id']);
        }
        return $this->fetch("mechanism/mechanismmember");
    }
    
    /**
     * 机构管理员状态
     * @return \think\response\Json
     */
    public function mechanismMemberStatus(){
        $params = input('param.');
        $mechanismMemberModel = new MechanismMemberModel();
        $res = $mechanismMemberModel->mechanismMemberStatus($params['num'], $params['id']);
        return json(['code' => $res['code'], 'data' => $res['data'], 'msg' => $res['msg']]);
    }
    
    /**
     * 编辑机构
     * @return array|mixed
     */
    public function mechanismEdit(){
        $mechanismModel = new MechanismModel();
        $areaModel = new AreaModel();
        if(Request::instance()->isAjax()){
            $params = input('param.');
            $data = [
                'mechanism_name' => $params['mechanism_name'],
                'mechanism_phone' => $params['mechanism_phone'],
                'mechanism_address' => $params['mechanism_address'],
                'mechanism_create_code' => $params['mechanism_create_code'],
                'mechanism_intro' => $params['content'],
                'mechanism_sheng' => $params['sheng'],
                'mechanism_shi' => $params['shi'],
                'mechanism_qu' => $params['qu'],
            ];
            if(!empty($params['images'])){
                $data['mechanism_logo'] = $params['images'];
            }
            $res = $mechanismModel->updateInfo($params['mechanism_id'], $data);
            if($res){
                return ['code' => 200, 'data' =>"", 'msg' => '修改成功'];
            }else{
                return ['code' => 100, 'data' => '', 'msg' => '修改失败'];
            }
        }
        $param = input('param.');
        $field = 'mechanism_id, mechanism_name, mechanism_phone, mechanism_address, 
        mechanism_create_code, mechanism_logo, mechanism_intro, mechanism_sheng, 
        mechanism_shi, mechanism_qu';
        $where['mechanism_id'] = $param['id'];
        $info = $mechanismModel->getOneInfo($where, $field);
        $province = $areaModel->getProvince();
        $city = $areaModel->getCity($info['mechanism_sheng']);
        $district = $areaModel->getdistrict($info['mechanism_shi']);
        $this->assign([
           'info' => $info,
            'province' => $province,
            'city' => $city,
            'district' => $district
        ]);
        return $this->fetch('mechanism/mechanismedit');
    }
}